package com.icecold.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sakura
 * @date 2024/9/30 14:11
 */
public class QRCodeGenerator2 {

    /**
     * @description: 生成二维码
     * @param text 二维码内容
     * @param remark 二维码描述
     * @param path 二维码保存路径
     * @param logoFile 二维码logo文件
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param fontSize 文字字号
     */
    public static void generateQRCode(String text, String[] remark, String path, File logoFile, int width, int height,Integer fontSize) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new ConcurrentHashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高纠错等级
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1); // 边框

        // 创建BitMatrix对象
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 动态计算增加的高度用于备注文本
        int textHeight = (remark != null && remark.length>0) ? 60*remark.length : 0;

        // 创建带有二维码和备注文本的 BufferedImage
        BufferedImage qrImage = new BufferedImage(width+300, height + textHeight+40, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = qrImage.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width+300, height + textHeight+40); // 设置背景为白色

        // 绘制二维码到 BufferedImage
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                qrImage.setRGB(150+x, 20+y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 添加Logo到二维码
        if (logoFile != null && logoFile.exists()) {
            addLogoToQRCode(qrImage, logoFile, width, height);
        }

        // 添加备注文本
        if (remark != null && remark.length>0) {
            if(fontSize == null){
                fontSize = 20;
            }
            addTextToQRCode(qrImage, remark, width, 20+height, textHeight,fontSize);
        }

        // 保存二维码图片到指定路径
        Path filePath = Paths.get(path);
        Files.createDirectories(filePath.getParent()); // 确保目录存在
        ImageIO.write(qrImage, "PNG", new File(path));
    }

    /**
     * @description: 生成二维码
     * @param text 二维码内容
     * @param remark 二维码描述
     * @param path 二维码保存路径
     */
    public static void generateQRCode(String text, String[] remark, String path) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new ConcurrentHashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高纠错等级
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1); // 边框

        int qrwidth = 350;
        int qrheight = 350;
        int width = 450;
        int height = 600;
        int padding = 20;

        // 创建BitMatrix对象
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrwidth, qrheight, hints);

        // 创建带有二维码和备注文本的 BufferedImage
        BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = qrImage.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height); // 设置背景为白色

        int qrx= 50;
        int qry= 0;
        if(remark != null && remark.length>0){
            qry= 55*remark.length;
        }

        // 绘制二维码到 BufferedImage
        for (int x = 0; x < qrwidth; x++) {
            for (int y = 0; y < qrheight; y++) {
                qrImage.setRGB(qrx+x, qry+y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }


        // 添加备注文本
        if (remark != null && remark.length>0) {
            addTextToQRCode(qrImage, remark);
        }

        // 保存二维码图片到指定路径
        Path filePath = Paths.get(path);
        Files.createDirectories(filePath.getParent()); // 确保目录存在
        ImageIO.write(qrImage, "PNG", new File(path));
    }

    // 添加Logo到二维码
    private static void addLogoToQRCode(BufferedImage qrImage, File logoFile, int qrWidth, int qrHeight) throws Exception {
        // 读取Logo图片
        BufferedImage logoImage = ImageIO.read(logoFile);

        // 计算Logo的缩放比例和新宽高
        int logoWidth = Math.min(logoImage.getWidth(), qrWidth / 5);  // 缩小至二维码宽度的1/5
        int logoHeight = Math.min(logoImage.getHeight(), qrHeight / 5);

        // 计算Logo绘制的左上角位置，使其居中
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;

        // 绘制白色边框背景
        Graphics2D g2 = qrImage.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(x - 5, y - 5, logoWidth + 10, logoHeight + 10, 10, 10);

        // 绘制Logo到二维码中心
        g2.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), x, y, null);
        g2.dispose();
    }

    // 在二维码底部添加文本
    private static void addTextToQRCode(BufferedImage image, String[] text, int width, int qrHeight, int textHeight,Integer fontSize) throws Exception {
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.BLACK);
        g2.setFont(new Font("宋体",  Font.BOLD, fontSize));  // 设置字体

        // 获取文本的宽度以便居中对齐
        FontMetrics fm = g2.getFontMetrics();
        int nextHeight = qrHeight;
        for (int i = 0; i < text.length; i++) {
            String text1 = text[i];
            int textWidth = fm.stringWidth(text1);
            int x = (width+300 - textWidth) / 2;

            // 调整 y 坐标位置，将文本稍微上移
            int padding = 10;  // 增加一个 padding 值，让文本上移一点，避免贴得太近
            nextHeight = nextHeight + (60 - fm.getHeight()) / 2 + fm.getAscent() - padding;

            // 绘制文本
            g2.drawString(text1, x, nextHeight);
            nextHeight+=20;
        }
        g2.dispose(); // 释放资源
    }

    // 在二维码底部添加文本
    private static void addTextToQRCode(BufferedImage image, String[] text) throws Exception {
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.BLACK);
        g2.setFont(new Font("黑体",  java.awt.Font.BOLD, 35));  // 设置字体

        // 获取文本的宽度以便居中对齐
        FontMetrics fm = g2.getFontMetrics();
        int nextHeight = 20;
        int x = 20;
        for (int i = 0; i < text.length; i++) {
            String text1 = text[i];
            int textWidth = fm.stringWidth(text1);


            // 调整 y 坐标位置，将文本稍微上移
            int padding = 10;  // 增加一个 padding 值，让文本上移一点，避免贴得太近
            nextHeight = nextHeight +25+ padding;

            // 绘制文本
            g2.drawString(text1, x, nextHeight);
            nextHeight+=10;
        }
        nextHeight+=(60+350);
        g2.setFont(new Font("黑体",  java.awt.Font.BOLD, 40));
        g2.drawString("扫码绑定获取权益", x, nextHeight);
        g2.dispose(); // 释放资源
    }

    /**
     * 生成普通黑白二维码
     */
    public static void putongErweima(String url,String outUrl) {
        try {
            // 准备一个Map集合，用来存储二维码图片的相关属性
            Map map = new HashMap();
            // 设置误差校验级别
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 设置字符编码（因为文本内容要转换成二维码，需要指定转换时采用的字符集）
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 设置二维码的外边距
            map.put(EncodeHintType.MARGIN, 1);


            // 创建MultiFormatWriter对象
            MultiFormatWriter writer = new MultiFormatWriter();
            // 传入：内容、码的格式、宽度、高度、二维码参数。返回位矩阵对象。
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            // 获取位矩阵的宽度和高度
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();

            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 遍历位矩阵
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    // 0xFF000000 黑色
                    // 0xFFFFFFFF 白色
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            // 输出
            FileOutputStream out = new FileOutputStream(new File(outUrl));
            ImageIO.write(image, "png", out);
            out.flush();
            out.close();

        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        putongErweima("https://www.zzlmvip.com?sn=32_AB_B1483E4609F47947-DISKSN", "D:\\images\\userfiles\\tmp\\2025-03-31\\ceshi.png");
    }

}

